<?php
class ModelLocalisationCurrency extends Model {
    public function addCurrency($data) {
        $this->db->query("INSERT INTO " . $this->db_prefix . "currency SET title = '" . $this->db->escape($data['title']) . "', code = '" . $this->db->escape($data['code']) . "', symbol_left = '" . $this->db->escape($data['symbol_left']) . "', symbol_right = '" . $this->db->escape($data['symbol_right']) . "', decimal_place = '" . $this->db->escape($data['decimal_place']) . "', value = '" . $this->db->escape($data['value']) . "', status = '" . (int)$data['status'] . "', date_modified = NOW()");

        if ($this->setting->get('config_currency_auto')) {
            $this->updateCurrencies(true);
        }

        $this->cache->delete('currency');
    }

    public function editCurrency($currency_id, $data) {
        $this->db->query("UPDATE " . $this->db_prefix . "currency SET title = '" . $this->db->escape($data['title']) . "', code = '" . $this->db->escape($data['code']) . "', symbol_left = '" . $this->db->escape($data['symbol_left']) . "', symbol_right = '" . $this->db->escape($data['symbol_right']) . "', decimal_place = '" . $this->db->escape($data['decimal_place']) . "', value = '" . $this->db->escape($data['value']) . "', status = '" . (int)$data['status'] . "', date_modified = NOW() WHERE currency_id = '" . (int)$currency_id . "'");

        $this->cache->delete('currency');
    }

    public function deleteCurrency($currency_id) {
        $this->db->query("DELETE FROM " . $this->db_prefix . "currency WHERE currency_id = '" . (int)$currency_id . "'");

        $this->cache->delete('currency');
    }

    public function getCurrency($currency_id) {
        $query = $this->db->query("SELECT DISTINCT * FROM " . $this->db_prefix . "currency WHERE currency_id = '" . (int)$currency_id . "'");

        return $query->row;
    }

    public function getCurrencyByCode($currency) {
        $query = $this->db->query("SELECT DISTINCT * FROM " . $this->db_prefix . "currency WHERE code = '" . $this->db->escape($currency) . "'");

        return $query->row;
    }

    public function getCurrencies($data = array()) {
        if ($data) {
            $sql = "SELECT * FROM " . $this->db_prefix . "currency";

            $sort_data = array(
                'title',
                'code',
                'value',
                'date_modified'
            );	

            if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
                $sql .= " ORDER BY " . $data['sort'];	
            } else {
                $sql .= " ORDER BY title";	
            }

            if (isset($data['order']) && ($data['order'] == 'DESC')) {
                $sql .= " DESC";
            } else {
                $sql .= " ASC";
            }

            if (isset($data['start']) || isset($data['limit'])) {
                if ($data['start'] < 0) {
                    $data['start'] = 0;
                }				

                if ($data['limit'] < 1) {
                    $data['limit'] = 20;
                }	

                $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
            }

            $query = $this->db->query($sql);

            return $query->rows;
        } else {
            $currency_data = $this->cache->get('currency');

            if (!$currency_data) {
                $currency_data = array();

                $query = $this->db->query("SELECT * FROM " . $this->db_prefix . "currency ORDER BY title ASC");

                foreach ($query->rows as $result) {
                    $currency_data[$result['code']] = array(
                        'currency_id'   => $result['currency_id'],
                        'title'         => $result['title'],
                        'code'          => $result['code'],
                        'symbol_left'   => $result['symbol_left'],
                        'symbol_right'  => $result['symbol_right'],
                        'decimal_place' => $result['decimal_place'],
                        'value'         => $result['value'],
                        'status'        => $result['status'],
                        'date_modified' => $result['date_modified']
                    );
                }	

                $this->cache->set('currency', $currency_data);
            }

            return $currency_data;			
        }
    }	

    public function updateCurrencies($force = false) {
        $data = array();

        if ($force) {

            $query = $this->pdo->prepare("SELECT * 
                FROM " . $this->db_prefix . "currency 
                WHERE code != :config_currency");

            $query->execute(array(
                ':config_currency'  => $this->setting->get('config_currency')
            ));
        } else {
            $query = $this->pdo->prepare("SELECT * 
                FROM " . $this->db_prefix . "currency 
                WHERE code != :config_currency 
                AND date_modified < :date");

            $query->execute(array(
                ':config_currency'  => $this->setting->get('config_currency'),
                ':date'             => date('Y-m-d H:i:s', strtotime('-1 day'))
            ));
        }

        if($query->rowCount() == 0){
            return true;
        }

        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        foreach ($result as $result) {
            $data[] = $this->setting->get('config_currency') . $result['code'] . '=X';
        }	

        $url = 'http://download.finance.yahoo.com/d/quotes.csv?s=' . implode(',', $data) . '&f=sl1&e=.csv';

        if(function_exists('curl_exec')) {            
            $curl = curl_init();

            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

            $content = curl_exec($curl);

            curl_close($curl);

        } else {
            // get the host name and url path
            $parsedUrl = parse_url($url);
            $host = $parsedUrl['host'];
            if (isset($parsedUrl['path'])) {
                $path = $parsedUrl['path'];
            } else {
                // the url is pointing to the host like http://www.mysite.com
                $path = '/';
            }

            if (isset($parsedUrl['query'])) {
                $path .= '?' . $parsedUrl['query'];
            }

            if (isset($parsedUrl['port'])) {
                $port = $parsedUrl['port'];
            } else {
                // most sites use port 80
                $port = '80';
            }

            $timeout = 10;
            $content = '';

            // connect to the remote server
            $fp = @fsockopen($host, '80', $errno, $errstr, $timeout );

            if( !$fp ) {
                $this->error_handler->write("Update Currency: cannot retrieve $url\n");
            } else {
                // send the necessary headers to get the file
                fputs($fp, "GET $path HTTP/1.0\r\n" .
                    "Host: $host\r\n" .
                    "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20140924 Firefox/24.0 Iceweasel/24.8.1\r\n" .
                    "Accept: */*\r\n" .
                    "Accept-Language: en-us,en;q=0.5\r\n" .
                    "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" .
                    "Keep-Alive: 300\r\n" .
                    "Connection: keep-alive\r\n" .
                    "Referer: http://$host\r\n\r\n");

                // retrieve the response from the remote server
                while ( $line = fread( $fp, 4096 ) ) {
                    $content .= $line;
                }

                fclose( $fp );

                // strip the headers
                $pos      = strpos($content, "\r\n\r\n");
                $content = substr($content, $pos + 4);
            }
        }

        $update = $this->pdo->prepare("UPDATE " . $this->db_prefix . "currency SET 
            value           = :value, 
            date_modified   = :date_modified  
            WHERE code      = :code");

        $lines = explode("\n", trim($content));
        foreach ($lines as $line) {
            $currency = utf8_substr($line, 4, 3);
            $value = utf8_substr($line, 11, 6);

            if ((float)$value) {
                $update->execute(array(
                    ':value'            => (float)$value, 
                    ':date_modified'    => date('Y-m-d H:i:s'),
                    ':code'             => $currency
                ));
            }
        }

        $update->execute(array(
            ':value'            => '1.00000', 
            ':date_modified'    => date('Y-m-d H:i:s'), 
            ':code'             => $this->setting->get('config_currency')
        ));

        $this->cache->delete('currency');
    }

    public function getTotalCurrencies() {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . $this->db_prefix . "currency");

        return $query->row['total'];
    }
}
?>
